﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

using AKMII.DMRA.Business.Rule;
using AKMII.DMRA.Common;
using AKMII.DMRA.DataAccess;

namespace AKMII.DMRA.DataLoader
{
    public class MailSender
    {
        public void Process(string type)
        {
            try
            {
                if (type.Equals("MarketDirector", StringComparison.CurrentCultureIgnoreCase))
                {
                    Logger.Info("Start sending reminder mail to MDs which have not orderred yet.");
                    UserAccessor accessor = new UserAccessor();
                    List<string> addresses = accessor.GetMailAddress(CurrentPeriod.Month, 
                        CurrentPeriod.Year, UserType.MarketDirector);
                    //List<string> CarbonCopys = accessor.GetMailAddress(UserType.Administrator);
                    if (addresses != null)
                    {
                        Mail mail = new Mail();
                        //mail.CarbonCopy = CarbonCopys;
                        mail.Subject = Constants.SubjectForReminderMail;
                        mail.Content = string.Format(Constants.ContentForReminderMail,
                            SystemConfiguration.MonthSettings.Find(delegate(MonthSetting setting) { return setting.MonthName == CurrentPeriod.Month; }).CutOffEndDate.ToString("dddd, MMM d, yyyy"));
                        foreach (var address in addresses)
                        {
                            mail.Recipients = new List<string>() { address };
                            Utility.Send(mail);
                            Logger.Info("Sending mail to " + address);
                            Thread.Sleep(60000);
                        }   
                    }
                    Logger.Info("End sending reminder mail to MDs which have not orderred yet.");
                }
                else if (type.Equals("Administrator", StringComparison.CurrentCultureIgnoreCase))
                {
                    Logger.Info("Start sending reminder mail to Division Admins that the MDs who have not orderred yet.");
                    UserAccessor accessor = new UserAccessor();
                    List<DivisionAdmin> listDivisionAdmin = accessor.GetAllDivisionAdmins();
                    List<string> users;
                    foreach (DivisionAdmin curDivisionAdmin in listDivisionAdmin)
                    {
                        string mdList = "{0}";
                        users = accessor.GetNames(CurrentPeriod.Month,
                            CurrentPeriod.Year, UserType.MarketDirector, curDivisionAdmin.DivisionNum);
                        if (users.Count > 0)
                        {
                            Mail mail = new Mail();
                            mail.Subject = "Order Reminder";
                            foreach (string name in users)
                            {
                               mdList += "        " + name + "\r\n";
                            }
                            string[] divName = curDivisionAdmin.DivisionalAdminName.Split(';');
                            string[] divEmail = curDivisionAdmin.EMail.Split(';');
                            var cutoffDateString = SystemConfiguration.MonthSettings.First(c => c.MonthName == CurrentPeriod.Month).CutOffEndDate.ToString("dddd, MMM d, yyyy");

                            for(int i=0;i<divEmail.Length;i++)
                            {
                             string curDivEmail=divEmail[i];
                             mail.Content = string.Format(mdList, "Dear " + divName[i] + ":\r\n     Following is a list of MDs in your division that haven't placed their order yet. This month’s lead order deadline is " + cutoffDateString + " by midnight (CST).\r\n");
                             mail.Recipients = new List<string>() { curDivEmail};
                             Utility.Send(mail);
                             Logger.Info("Sent Division Reminder mail to Div Admin \"" + curDivisionAdmin.AccountID + "\" \"" + curDivEmail+ "\"");
                             Thread.Sleep(30000);
                            }                           
                        }
                        else
                        {
                            Logger.Info("All MD belongs to Div Admin \"" + curDivisionAdmin.AccountID + "\" have already orderred.");
                        }
                    }
                    Logger.Info("End sending reminder mail to Division Admins that the MDs who have not orderred yet.");
                }
                else if (type.Equals("Summary", StringComparison.CurrentCultureIgnoreCase))
                {
                    Logger.Info("Start sending Summary mail to Summary Report Receiver.");
                    OrderAccessor orderAccessor = new OrderAccessor();
                    string path = Path.Combine(SystemConfiguration.CommonSetting.FolderForSummaryReport,
                        string.Format(Constants.FileNameForSummaryToAdmin, Utility.GetNumber(CurrentPeriod.Month), Utility.GetNumber(CurrentPeriod.Year)));
                    DateTime currentDate = Convert.ToDateTime(CurrentPeriod.Year + "-" + CurrentPeriod.Month + "-" + "1");
                    List<List<Order>> allOrders = new List<List<Order>>();
                    List<string> sheetNames = new List<string>();

                    for (int i = 0; i > -12; i--)
                    {
                        List<Order> orders = orderAccessor.GetOrders(currentDate.AddMonths(i).Month,
                            currentDate.AddMonths(i).Year);

                        sheetNames.Add(Utility.GetNumber(currentDate.AddMonths(i).Month) + " " + Utility.GetNumber(currentDate.AddMonths(i).Year));
                        allOrders.Add(orders);
                    }

                    Utility.GenerateReport(allOrders, sheetNames, path);

                    Mail mail = new Mail();
                    mail.Subject = "Order Summary";
                    mail.Content = "Please check the attachment for Order Summary Report.";
                    mail.Recipients = new List<string>() { SystemConfiguration.CommonSetting.MailAddressForSummaryReport };
                    mail.AttachmentFile = path;
                    Utility.Send(mail);

                    /**
                    List<OrderInfo> orderInfos = orderAccessor.GetOrderInfo(CurrentPeriod.Month, CurrentPeriod.Year);
                    path = Path.Combine(SystemConfiguration.CommonSetting.FolderForSummaryReport,
                        string.Format(Constants.FileNameForMdSummary, Utility.GetNumber(CurrentPeriod.Month), Utility.GetNumber(CurrentPeriod.Year)));
                    Utility.GenerateReport(orderInfos, path);

                    mail = new Mail();
                    mail.Subject = "Order Infomation";
                    mail.Content = "Please check the attachment for Order Information Report.";
                    mail.Recipients = new List<string>() { SystemConfiguration.CommonSetting.MailAddressForSummaryReport };
                    mail.AttachmentFile = path;
                    Utility.Send(mail);
                    
                    List<OrderInfo> orderInfos = orderAccessor.GetOrderMoreInfo(CurrentPeriod.Month, CurrentPeriod.Year);
                    path = Path.Combine(SystemConfiguration.CommonSetting.FolderForSummaryReport,
                        string.Format(Constants.FileNameForMdSummary, Utility.GetNumber(CurrentPeriod.Month), Utility.GetNumber(CurrentPeriod.Year)));
                    Utility.GenerateReport(orderInfos, path);

                    mail = new Mail();
                    mail.Subject = "Order Infomation";
                    mail.Content = "Please check the attachment for Order Information Report.";
                    mail.Recipients = new List<string>() { SystemConfiguration.CommonSetting.MailAddressForSummaryReport };
                    mail.AttachmentFile = path;
                    Utility.Send(mail);
                    **/
                    List<RepeatReason> reasons = orderAccessor.GetRepeatOrderReason(CurrentPeriod.Month, CurrentPeriod.Year);
                    path = Path.Combine(SystemConfiguration.CommonSetting.FolderForSummaryReport,
                        string.Format(Constants.FileNameForRepeatOrder, Utility.GetNumber(CurrentPeriod.Month), Utility.GetNumber(CurrentPeriod.Year)));
                    Utility.GenerateReport(reasons, path);

                    mail = new Mail();
                    mail.Subject = "Repeat Order Reason";
                    mail.Content = "Please check the attachment for Repeat Order.";
                    mail.Recipients = new List<string>() { SystemConfiguration.CommonSetting.MailAddressForSummaryReport };
                    mail.AttachmentFile = path;
                    Utility.Send(mail);

                    Logger.Info("End sending Summary mail to Summary Report Receiver.");
                }
                else if (type.Equals("Weekly", StringComparison.CurrentCultureIgnoreCase))
                {
                    Logger.Info("Start sending Weekly reminder mail to all MD and Admins.");
                    UserAccessor accessor = new UserAccessor();
                    List<string> addresses = new List<string>();
                    addresses.AddRange(accessor.GetMailAddress(UserType.MarketDirector));
                    addresses.AddRange(accessor.GetMailAddress(UserType.Administrator));

                    MonthSetting currentMonthSetting = SystemConfiguration.MonthSettings.Find(
                        delegate(MonthSetting setting) { return setting.MonthName == (CurrentPeriod.Month == 12 ? 1 : CurrentPeriod.Month + 1); });
                    Mail mail = new Mail();
                    mail.Subject = Constants.SubjectForWeeklyReminderMail;
                    mail.Content = string.Format(Constants.ContentForWeeklyReminderMail, Utility.GetMonthName(currentMonthSetting.MonthName),
                        currentMonthSetting.CutOffStartDate.ToString("MM/dd/yyyy"), currentMonthSetting.CutOffEndDate.ToString("MM/dd/yyyy"));

                    if (addresses != null)
                    {
                        foreach (var address in addresses)
                        {
                            mail.Recipients = new List<string>() { address };
                            Utility.Send(mail);

                            Logger.Info("Sending mail to " + address);
                            Thread.Sleep(30000);
                        }
                    }

                    Logger.Info("End sending Weekly reminder mail to all MD and Admins.");
                }
                else
                {
                    // Noting to do.
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Exception occurs in send reminder mail", ex);
            }
        }
    }
}
